#include "ILAppBase.h"


DEMO_APP s_demo_app;
/*
 *	modify this function according to every project
 *	ie: DEMO_APP * app_ptr
 */
ILINT il_get_layer_hdlr_by_buffer(ILUINT8* buffer)
{
	ILUINT8* tmp_buffer = NULL;
	DEMO_APP* app_ptr = il_get_app_instance();
	ILINT i = 0;

	if(!buffer)
		return -1;

	for(i = 0; i < ARRAY_SIZE(app_ptr->layer_hdl); i++)
	{
		tmp_buffer = vm_graphic_get_layer_buffer(app_ptr->layer_hdl[i]);

		if(tmp_buffer == buffer)
		{
			return app_ptr->layer_hdl[i];
		}
	}

	return -1;
}

/*
 *	modify this function accorrding to every projects
 */
DEMO_APP* il_get_app_instance(void)
{
	return &s_demo_app;
}
/************************************************************************/
/* common part                                                          */
/************************************************************************/

static il_rect s_il_clip_area;
static volatile ILUINT8 s_is_flush = TRUE;

static il_ret il_set_layer_clip(ILINT layer, ILINT16 x, ILINT16 y, ILINT16 w, ILINT16 h)
{
	ILINT16 _x1, _y1, _x2, _y2;

	if(layer < 0)
		return IL_INVALID_PARAM;

	if(y > s_il_clip_area.y + s_il_clip_area.h - 1
		|| y + h - 1 < s_il_clip_area.y
		|| x > s_il_clip_area.x + s_il_clip_area.w - 1
		|| x + w - 1 < s_il_clip_area.x)
		return IL_IGNORE;

	_x1 = IL_MAX(x, s_il_clip_area.x);
	_y1 = IL_MAX(y, s_il_clip_area.y);
	_x2 = IL_MIN(x + w, s_il_clip_area.x + s_il_clip_area.w) - 1;
	_y2 = IL_MIN(y + h, s_il_clip_area.y + s_il_clip_area.h) - 1;
	s_il_clip_area.x = _x1;
	s_il_clip_area.y = _y1;
	s_il_clip_area.w = _x2 + 1 - _x1;
	s_il_clip_area.h = _y2 + 1 - _y1;
	vm_graphic_set_layer_clip(layer, _x1, _y1, _x2, _y2);
	return IL_OK;
}

il_ret il_set_layer_clip_ex(ILINT layer, const il_rect* area_p)
{
	if(!area_p)
		return IL_INVALID_PARAM;

	return il_set_layer_clip(layer, area_p->x, area_p->y, area_p->w, area_p->h);
}

void il_get_global_clip(il_rect* clip_p)
{
	if(clip_p)
	{
		memcpy(clip_p, &s_il_clip_area, sizeof(il_rect));
	}
}

void il_reset_layer_clip(ILINT layer)
{
	if(layer < 0)
		return;

	s_il_clip_area.x = 0;
	s_il_clip_area.y = 0;
	s_il_clip_area.w = vm_graphic_get_screen_width();
	s_il_clip_area.h = vm_graphic_get_screen_height();
	il_set_layer_clip_ex(layer, &s_il_clip_area);
}

void il_fill_rect(ILUINT8* buf, const il_rect* area_p, ILUINT16 line_color, ILUINT16 fill_color)
{
	if(!buf || !area_p)
		return;

	vm_graphic_fill_rect(buf, area_p->x, area_p->y, area_p->w, area_p->h, line_color, fill_color);
}


void il_disable_flush(void)
{
	if (s_is_flush)
		s_is_flush = FALSE;
}

void il_enable_flush(void)
{
	if (!s_is_flush)
		s_is_flush = TRUE;
}

ILINT il_get_flush_status(void)
{
	return s_is_flush;
}

void il_flush(void)
{
	DEMO_APP* app_ptr = il_get_app_instance();
	if(!il_get_flush_status())
		return;

	vm_graphic_flush_layer(app_ptr->layer_hdl, sizeof(app_ptr->layer_hdl));
}